import { reactive, computed } from 'vue'
import { userApi } from '../services/api'
import router from '../router'

// 创建响应式状态
const state = reactive({
  currentUser: null,
  loading: true
})

// 用户状态管理
const userStore = {
  // 响应式状态
  currentUser: computed(() => state.currentUser),
  loading: computed(() => state.loading),
  
  // 计算属性
  isLoggedIn: computed(() => !!state.currentUser),
  isAdmin: computed(() => state.currentUser?.role === 'admin'),
  
  // 检查token并加载用户信息
  checkAuth() {
    const token = localStorage.getItem('token')
    if (token) {
      this.loadCurrentUser(token)
      return true
    } else {
      state.loading = false
      return false
    }
  },
  
  // 从token加载用户信息
  async loadCurrentUser(token) {
    try {
      // 从token中解析用户信息
      const user = JSON.parse(atob(token.split('.')[1]))
      if (user) {
        state.currentUser = {
          id: user.sub,
          username: user.unique_name,
          role: user['http://schemas.microsoft.com/ws/2008/06/identity/claims/role']?.toLowerCase() || 'user'
        }
      } else {
        throw new Error('用户信息不完整')
      }
    } catch (error) {
      console.error('获取用户信息失败:', error)
      state.currentUser = null
      localStorage.removeItem('token')
      router.push('/login')
    } finally {
      state.loading = false
    }
  },
  
  // 登录
  async login(userData) {
    try {
      const response = await userApi.login(userData)
      if (response.data && response.data.user && response.data.user.role) {
        localStorage.setItem('token', response.data.token)
        state.currentUser = {
          id: response.data.user.id,
          username: response.data.user.username,
          role: response.data.user.role
        }
        return { success: true }
      } else {
        throw new Error('登录响应数据不完整')
      }
    } catch (error) {
      console.error('登录失败:', error)
      return {
        success: false,
        message: error.response?.data?.message || '登录失败'
      }
    }
  },
  
  // 登出
  logout() {
    localStorage.removeItem('token')
    state.currentUser = null
    router.push('/login')
  }
}

// 导出userStore对象
export default userStore